package com.wanpinghui.supplier.message;

import android.content.Intent;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.malinskiy.superrecyclerview.SuperRecyclerView;
import com.netease.nimlib.sdk.RequestCallback;
import com.netease.nimlib.sdk.uinfo.model.NimUserInfo;
import com.wanpinghui.supplier.Config;
import com.wanpinghui.supplier.R;
import com.wanpinghui.supplier.common.BaseFragment;
import com.wanpinghui.supplier.message.adapter.RecentMsgAdapter;
import com.wanpinghui.supplier.message.nim.NimManager;
import com.wanpinghui.supplier.message.nim.WPHMsg;
import com.wanpinghui.supplier.oauth.LoginActivity;
import com.wanpinghui.supplier.oauth.LoginUtil;
import com.wanpinghui.supplier.object.HomePageActivity;
import com.wanpinghui.supplier.object.ObjectListActivity;
import com.wanpinghui.supplier.widgets.SpinView;
import com.wanpinghui.wphlibrary.WPHSdk;
import com.wanpinghui.wphlibrary.model.message.MessageService;
import com.wanpinghui.wphlibrary.model.message.bean.MessageType;
import com.wanpinghui.wphlibrary.model.message.bean.MsgBean;
import com.wanpinghui.wphlibrary.model.message.bean.RecentMsgBean;
import com.wanpinghui.wphlibrary.widgets.ThrottleButton;
import com.yunshl.yunshllibrary.recyclerview.OnItemClickListener;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.List;

import retrofit.callback.YRequestCallback;

/***
 * 功能描述:
 * 作者:qiujialiu
 * 时间:2017/11/23
 ***/
@ContentView(R.layout.layout_fragment_message)
public class MessageFragment extends BaseFragment implements NimManager.INIMListener, YRequestCallback<List<RecentMsgBean>>, NimManager.INIMRcvMsgListener {
    @ViewInject(R.id.sv)
    private SpinView sv;

    @ViewInject(R.id.tv_msg_title)
    private TextView tv_msg_title;

    @ViewInject(R.id.recv_msg_list)
    private SuperRecyclerView recv_msg_list;

    @ViewInject(R.id.ll_empty_view)
    private LinearLayout ll_empty_view;

    @ViewInject(R.id.rl_tip_area)
    private RelativeLayout rl_tip_area;

    @ViewInject(R.id.tv_msg_tip)
    private TextView tv_msg_tip;

    @ViewInject(R.id.btn_login)
    private ThrottleButton btn_login;

    @ViewInject(R.id.iv_filter)
    private ImageView iv_filter;

    private String mCustomerId = "4";

    private RecentMsgAdapter mAdapter = null;
    private boolean isResumed;

    List<RecentMsgBean> datas = new ArrayList<>();

    private SwipeRefreshLayout.OnRefreshListener refreshListener;

    @Override
    public void init() {
        bindEvent();
        mAdapter = new RecentMsgAdapter(getActivity());
        recv_msg_list.setLayoutManager(new LinearLayoutManager(getActivity()));
        recv_msg_list.setAdapter(mAdapter);
        refreshListener = new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        getData();
                    }
                }, 1000);
            }
        };
        recv_msg_list.setLayoutManager(new LinearLayoutManager(this.getContext()));
        recv_msg_list.setRefreshListener(refreshListener);
        recv_msg_list.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                if (mAdapter.getDatas().size() > 0)
                    onRescentMsgBeanClick((RecentMsgBean) mAdapter.getDatas().get(position));
            }
        });
        iv_filter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (LoginUtil.isLogin())
                    MessageP2PActivity.start(getActivity(), mCustomerId, MsgBean.getGroupId(mCustomerId, WPHMsg.TYPE_SERVICE));
                else
                    startActivity(new Intent(getActivity(), LoginActivity.class));
            }
        });
        //testData();
    }


    private void onRescentMsgBeanClick(RecentMsgBean recentMsgBean) {

        switch (recentMsgBean.getMsg_type()) {
            case MessageType.TYPE_NEW_OBJECT://新订单提醒
            case MessageType.TYPE_NEW_OBJECT_DISPATCH:
            case MessageType.TYPE_NEW_OBJECT_FREE_SEND:
                goNewFindOrder(recentMsgBean);
                break;
            case MessageType.TYPE_NORMAL://普通聊天
                getP2PChat(recentMsgBean);
                break;
            case MessageType.TYPE_BID_SUCCESS://竞标成功提醒
                goBidSucNotification(recentMsgBean);
                break;
            case MessageType.TYPE_SERVICE://客服
                getP2PChat(recentMsgBean);
                break;
        }
    }

    private void getP2PChat(RecentMsgBean recentMsgBean) {
        WPHSdk.getService(MessageService.class).updateRecentMsgUnRead(recentMsgBean);
        mAdapter.notifyDataSetChanged();
        MessageP2PActivity.start(this.getActivity(), recentMsgBean.getChatImId(), recentMsgBean.getGroup_id());

    }

    private void goBidSucNotification(RecentMsgBean recentMsgBean) {
        WPHSdk.getService(MessageService.class).updateRecentMsgUnRead(recentMsgBean);
        mAdapter.notifyDataSetChanged();
        Intent intent = new Intent(getActivity(), BidSucNotificationActivity.class);
        intent.putExtra("groupId", recentMsgBean.getGroup_id());
        startActivity(intent);
    }

    private void goNewFindOrder(RecentMsgBean recentMsgBean) {
        WPHSdk.getService(MessageService.class).updateRecentMsgUnRead(recentMsgBean);
        mAdapter.notifyDataSetChanged();
        if (Config.VERSION < 3) {
            ((HomePageActivity) getActivity()).setUpdateCount();
            ((HomePageActivity) getActivity()).goPage(Config.getObjectPage());
            ((HomePageActivity) getActivity()).setMessageCount(getMessageCount());
        }else {
            Intent intent = new Intent(getActivity(), ObjectListActivity.class);
            startActivity(intent);
        }
        //ActivityJumpUtil.startObjectList(this.getContext());
    }

    private void reflash() {

        recv_msg_list.getSwipeToRefresh().post(new Runnable() {
            @Override
            public void run() {
                recv_msg_list.setRefreshing(true);//执行下拉刷新的动画
                refreshListener.onRefresh();//执行数据加载操作
            }
        });
    }

    private void getData() {
        WPHSdk.getService(MessageService.class).getRecentMsgBeanList(this);
    }

    private void bindEvent() {
        btn_login.setOnThrottleClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getActivity(), LoginActivity.class));
            }
        });

    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            NimManager.getInstance().enterRecentChat();
            checkConnectStatu();
            NimManager.getInstance().registerRcvListener(null, this);
            updateData();
        } else {
            NimManager.getInstance().quitChat();
        }
        NimManager.getInstance().regOrUnregOnline(this, isVisibleToUser);
    }

    @Override
    public void onResume() {
        super.onResume();
        NimManager.getInstance().enterRecentChat();
        checkConnectStatu();
        updateData();
        if (!isResumed) {
            if (LoginUtil.isLogin()) {
                reflash();
            }
            isResumed = true;
        }
    }

    private void updateData() {
        if (recv_msg_list != null) {
            datas = WPHSdk.getService(MessageService.class).getRecentMsgBeanCacheData();
            recv_msg_list.setRefreshing(false);
            mAdapter.setDatas(datas);
            updateView();
        }
    }

    private void checkConnectStatu() {
        if (rl_tip_area != null) {
            boolean connected = NimManager.getInstance().isOnline();
            rl_tip_area.setVisibility(View.GONE);
            if (connected) {
                sv.setVisibility(View.GONE);
                tv_msg_title.setText("消息");
                NimManager.getInstance().initIncommingRcvObserver();
            } else {
                sv.setVisibility(View.GONE);
                tv_msg_title.setText("消息(未连接)");
            }
        }
    }

    @Override
    public void onConnecting() {
        rl_tip_area.setVisibility(View.GONE);
        sv.setVisibility(View.VISIBLE);
        tv_msg_title.setText("连接中...");
    }

    @Override
    public void onConnected() {
        rl_tip_area.setVisibility(View.GONE);
        sv.setVisibility(View.GONE);
        tv_msg_title.setText("消息");
    }

    @Override
    public void onWaringTip(String msg, boolean reqLogin) {
        rl_tip_area.setVisibility(View.GONE);
        sv.setVisibility(View.GONE);
        tv_msg_title.setText("消息(未连接)");
        tv_msg_tip.setText(msg);
        if (reqLogin)
            btn_login.setVisibility(View.VISIBLE);
        else
            btn_login.setVisibility(View.GONE);

    }

    @Override
    public void onSuccess(List<RecentMsgBean> var1) {
        recv_msg_list.setRefreshing(false);
        mAdapter.setDatas(var1);
        updateView();
        if (var1 != null && var1.size() > 0) {
            NimManager.getInstance().initAccount(var1, new RequestCallback<List<NimUserInfo>>() {
                @Override
                public void onSuccess(List<NimUserInfo> param) {
                    mAdapter.notifyDataSetChanged();
                }

                @Override
                public void onFailed(int code) {

                }

                @Override
                public void onException(Throwable exception) {

                }
            });
        }
    }

    @Override
    public void onFailed(int var1, String message) {
        recv_msg_list.setRefreshing(false);
        updateView();
    }

    @Override
    public void onException(Throwable var1) {
        recv_msg_list.setRefreshing(false);
        updateView();
    }

    private void updateView() {
        List<RecentMsgBean> datas = mAdapter.getDatas();
        if (datas != null && datas.size() > 0) {
            ll_empty_view.setVisibility(View.GONE);
            recv_msg_list.setVisibility(View.VISIBLE);
        } else {
            ll_empty_view.setVisibility(View.VISIBLE);
            recv_msg_list.setVisibility(View.GONE);
        }
        try {
            if (LoginUtil.isLogin())
                ((HomePageActivity) getActivity()).setMessageCount(getMessageCount());
            else
                ((HomePageActivity) getActivity()).setMessageCount(0);
        } catch (Exception e) {
        }
    }

    @Override
    public void onMsgRcv(List<MsgBean> datas) {
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void onRecentMsgRcv(List<RecentMsgBean> datas) {
        recv_msg_list.setRefreshing(false);
        mAdapter.setDatas(datas);
        updateView();
    }

    private int getMessageCount() {

        int count = 0;

        List<RecentMsgBean> datas = mAdapter.getDatas();

        if (datas != null && datas.size() > 0) {

            for (RecentMsgBean rmb : datas) {

                count = count + rmb.getUn_read_count();
            }
        }

        return count;
    }

}
